#pragma once
#include <memory>
#include "socket.hpp"
#include "InetAddr.hpp"
using namespace socket_ns;
class Listener
{
public:
    Listener(uint16_t port)
        : _port(port), _listensock(std::make_unique<TcpSocket>())
    {
        _listensock->BuildListenSocket(port);
    }

    int Listenfd()
    {
        return _listensock->Sockfd();
    }

    void Accepter(Connection *conn)
    {
        while (true)
        {
            errno = 0; // 将错误码设为0，防止之前异常的错误码影响
            int code = 0;
            InetAddr addr;
            int sockfd = _listensock->Accepter(&addr, &code);
            if (sockfd > 0)
            {
                // 将fd添加到内核中
                conn->_R->AddConnection(sockfd, EPOLLIN | EPOLLET, NormalConnection);
            }
            else
            {
                if (code == EWOULDBLOCK)
                {
                    LOG(INFO, "底层连接全部获取完毕\n");
                    break;
                }
                else if (code == EINTR)
                {
                    continue;
                }
                else
                {
                    LOG(ERROR, "获取连接失败,errno:%d!\n", code);
                    break;
                }
            }
        }
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensock;
};
